package com.autohelper.app.tcp.protocol;




import com.autohelper.app.tcp.model.Message;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

public class MessageDecoder extends LengthFieldBasedFrameDecoder {
    public MessageDecoder() {
        super(1024 * 1024 * 10, 16, 4);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf frame = (ByteBuf) super.decode(ctx, in);
        if (frame == null) {
            return null;
        }
        frame.skipBytes(4);
        long reqId = frame.readLong();
        short version = frame.readShort();
        short command = frame.readShort();
        int length = frame.readInt();
        byte[] content = new byte[length];
        frame.readBytes(content);

        Message message = new Message();
        message.setReqId(reqId);
        message.setVersion(version);
        message.setCommand(command);
        message.setLength(length);
        message.setContent(content);

        return message;
    }
}